﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BoolanSlide.FileManager;
using BoolanSlide.FileStruct;
using Configuration;
using Windows.Storage;
using Windows.UI.Xaml;

namespace BoolanElement.Storage
{
    public static class AutoSaveHelper
    {
        static List<string> SavedCopiesName;
        private const int MaxCopiesNum = 1;


        static string SavedName = ".Saved.bak.si";
        static string SavingName = ".Saving.bak.si";

        private const int TimerInvokeInterval = 30; //秒


        private static DispatcherTimer timer;

        static bool CanRename = false;


        public static StorageFile BakFile = null;

        public static bool ShouldBeSaved = true;

        static AutoSaveHelper()
        {
            SavedCopiesName = new List<string>();

            timer = new DispatcherTimer();

            timer.Interval = new TimeSpan(0, 0, TimerInvokeInterval);
            timer.Tick += timer_Tick;
        }

        static async void timer_Tick(object sender, object e)
        {
            if (!ShouldBeSaved)
                return;
            await StorageLock.AutoSaveWholeWaitSignal.WaitAsync();
            if (ShouldBeSaved)
            {
                ShouldBeSaved = false;
                await AutoSave();
                ShouldBeSaved = true;
            }
            StorageLock.AutoSaveWholeWaitSignal.Release();
        }

        public static async Task<bool> AutoSave()
        {
            if (GlobalVariable.OpenedDocument == null)
                return false;

            StorageFolder folder=await BooUtility.GetFolderFromDocumentFolderAsync(BooDocumentHelper.BakFolder);
            await DocumentStorage.Save(GlobalVariable.OpenedDocument,folder, SavingName);

            if (CanRename == true)
            {
                BakFile = await UpdateBakFile();
            }
            return true;
        }

        public static void StartupAutoSave()
        {
            if (CanRename == true)
                return;
           
            //timer.Start();
            CanRename = true;
        }

        public static void PauseAutoSave()
        {
            if (timer.IsEnabled == true)
            {
                timer.Stop();
            }
            CanRename = false;
        }

        public static async Task<bool> ShutdownAutoSave()
        {
            if (timer.IsEnabled == true)
            {
                timer.Stop();
                await CleanBak(SavedCopiesName, 0, SavedCopiesName.Count);
            }
            await CleanBak();
            CanRename = false;
            return true;
        }

        private static async Task<bool> CleanBak(List<string> copyList, int begin, int end)
        {
            await StorageLock.AutoSaveWaitSignal.WaitAsync();
            StorageFolder folder = await BooUtility.GetFolderFromDocumentFolderAsync(BooDocumentHelper.BakFolder);
            IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();

            foreach (var itemFile in fileList)
            {
                for (int i = begin; i < end; i++)
                {
                    if (copyList[i] == itemFile.Name)
                    {
                        await itemFile.DeleteAsync( StorageDeleteOption.PermanentDelete);
                        break;
                    }
                }
            }

            copyList.RemoveRange(begin, end - begin);
            StorageLock.AutoSaveWaitSignal.Release();
            return true;
        }

        private static async Task<bool> CleanBak()
        {
            await StorageLock.AutoSaveWaitSignal.WaitAsync();
            StorageFolder folder = await BooUtility.GetFolderFromDocumentFolderAsync(BooDocumentHelper.BakFolder);

            IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();

            foreach (var itemFile in fileList)
            {
                if (itemFile.Name == SavedName || itemFile.Name == SavingName)
                {
                    await itemFile.DeleteAsync();
                }
            }
            StorageLock.AutoSaveWaitSignal.Release();
            return true;
        }

        private static async Task<StorageFile> UpdateBakFile()
        {
            await StorageLock.AutoSaveWaitSignal.WaitAsync();
            StorageFolder folder = await BooUtility.GetFolderFromDocumentFolderAsync(BooDocumentHelper.BakFolder);
            IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();

            foreach (var item in files)
            {
                if (item.Name == SavingName)
                {
                    await item.RenameAsync(SavedName, NameCollisionOption.ReplaceExisting);
                    StorageLock.AutoSaveWaitSignal.Release();
                    return item;
                }
            }
            StorageLock.AutoSaveWaitSignal.Release();
            return null;
        }
    }
}
